#include "udp.h"
#include <QJsonDocument>
#include <QJsonObject>
static const unsigned BROADCASTPORT2 = 45001;
udp::udp(QObject *parent)  : QObject(parent)
{
    broadcastSocket.bind(QHostAddress::Any, BROADCASTPORT2, QUdpSocket::ShareAddress
                         | QUdpSocket::ReuseAddressHint);

    connect(&broadcastSocket, SIGNAL(readyRead()), this, SLOT(readBroadcastDatagram()));

}

void udp::post(const QString &address, const QVariantMap &message)
{
    QJsonDocument document(QJsonObject::fromVariantMap(message));
    QByteArray d = document.toJson();
    qint64 wr = broadcastSocket.writeDatagram(d, QHostAddress(address) ,
                                  BROADCASTPORT2);

    qInfo() << "#write:" << d.size() << " real：" << wr;
}

void udp::readBroadcastDatagram()
{
    while (broadcastSocket.hasPendingDatagrams()) {
        QHostAddress senderIp;
        quint16 senderPort;
        QByteArray datagram;

        datagram.resize(broadcastSocket.pendingDatagramSize());
        if (broadcastSocket.readDatagram(datagram.data(), datagram.size(),
                                         &senderIp, &senderPort) == -1)
            continue;

        QJsonDocument document = QJsonDocument::fromJson(datagram);

        qInfo() << "#info:" << senderIp << ":" << datagram;

        emit newMessage(senderIp.toString(), document.object().toVariantMap());
        }

}

